<?php

namespace app\admin\service\auth;

use app\admin\service\AdminTokenService;
use tmcore\base\BaseService;
use app\common\model\auth\SystemRole;
use app\common\cache\AdminAuthCache;
use app\common\enum\YesNoEnum;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminRole;

/**
 * 管理员服务类
 */
class AdminService extends BaseService
{
    /**
     * 获取管理员列表
     * @return array
     */
    public static function getList(): array
    {
        // 接受参数
        $params = request()->get();

        // 搜索条件
        $searchParam = [
            '%like%' => ['name', 'account'],
            '=' => ['disable', 'dept_id', 'jobs_id']
        ];
        $where = self::getSearchData($searchParam);
        if (isset($params['role_id']) && $params['role_id'] != '') {
            $adminIds = AdminRole::where('role_id', $params['role_id'])->column('admin_id');
            if (!empty($adminIds)) {
                $where[] = ['id', 'in', $adminIds];
            }
        }

        // 角色数组（'角色id'=>'角色名称')
        $roleLists = SystemRole::column('name', 'id');

        // 返回分页数据
        $list = Admin::page($where, self::getPageData(),
            ['id', 'name', 'account', 'create_time', 'disable', 'dept_id', 'jobs_id', 'root', 'login_time', 'login_ip', 'multipoint_login'],
            ['id' => 'desc'],
            ['role_id', 'dept_id', 'jobs_id', 'disable_desc', 'dept_name', 'jobs_name']
        );

        foreach ($list['list'] as &$item) {
            $roleName = '';
            if ($item['root'] == 1) {
                $roleName = '系统管理员';
            } else {
                foreach ($item['role_id'] as $roleId) {
                    $roleName .= $roleLists[$roleId] ?? '';
                    $roleName .= '/';
                }
            }

            $item['role_name'] = trim($roleName, '/');
        }

        return $list;
    }

    /**
     * 添加管理员
     * @param array $params
     * @param bool $is_root
     * @return bool
     */
    public static function add(array $params, bool $is_root = false)
    {
        self::beginTrans();
        try {
            $passwordSalt = com_get_config('unique_identification', 'core');
            $password = password_encrypt($params['password'], $passwordSalt);

            if($is_root && Admin::where(['root' => 1])->count()) {
                throw new \Exception("超级管理员不可重复添加");
            }

            // 添加管理员
            $admin = Admin::create([
                'root' => $is_root?1:0,
                'name' => $params['name'],
                'account' => $params['account'],
                'password' => $password,
                'disable' => $params['disable'],
                'dept_id' => $params['dept_id'],
                'jobs_id' => $params['jobs_id'],
                'multipoint_login' => $params['multipoint_login'],
                'mobile' => $params['mobile'],
                'email' => $params['email'],
            ]);

            // 添加角色关联
            self::insertRole($admin['id'], $params['role_id'] ?? []);

            self::commitTrans();
            return true;
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setError($e->getMessage());
        }
    }


    /**
     * 编辑管理员
     * @param array $params
     * @return bool
     */
    public static function edit(array $params): bool
    {
        self::beginTrans();
        try {
            $passwordSalt = com_get_config('unique_identification', 'core');
            $password = password_encrypt($params['password'], $passwordSalt);

            // 基础信息
            $data = [
                'id' => $params['id'],
                'name' => $params['name'],
                'account' => $params['account'],
                'password' => $password,
                'disable' => $params['disable'],
                'dept_id' => $params['dept_id'],
                'jobs_id' => $params['jobs_id'],
                'multipoint_login' => $params['multipoint_login'],
                'mobile' => $params['mobile'],
                'email' => $params['email'],
            ];

            // 禁用或更换角色后.设置token过期
            $roleId = AdminRole::where('admin_id', $params['id'])->column('role_id');
            $editRole = false;
            if (!empty(array_diff_assoc($roleId, $params['role_id']))) $editRole = true;

            if ($params['disable'] == 1 || $editRole) {
                AdminTokenService::clearToken($params['id']);
            }

            Admin::update($data);

            // 清理管理员缓存
            (new AdminAuthCache($params['id']))->deleteAuthUserCache();

            // 删除旧的关联信息
            AdminRole::delByUserId($params['id']);
            // 添加角色关联
            self::insertRole($params['id'], $params['role_id']);

            self::commitTrans();
            return true;
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setError($e->getMessage());
        }
    }


    /**
     * 删除管理员
     * @param array $params
     * @return bool
     */
    public static function delete(array $params): bool
    {
        self::beginTrans();
        try {
            $admin = Admin::findOrEmpty($params['id']);
            if ($admin->root == YesNoEnum::YES) {
                throw new \Exception("超级管理员不允许被删除");
            }
            Admin::destroy($params['id']);

            AdminTokenService::clearToken($params['id']);

            // 清理管理员缓存
            (new AdminAuthCache($params['id']))->deleteAuthUserCache();

            // 删除旧的关联信息
            AdminRole::delByUserId($params['id']);

            self::commitTrans();
            return true;
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 查看管理员详情
     * @param $params
     * @return array
     */
    public static function detail($params, $action = 'detail'): array
    {
        $admin = Admin::field([
            'id', 'account', 'name', 'disable', 'root', 'multipoint_login' , 'dept_id' , 'jobs_id', 'mobile', 'email', 'login_time', 'login_ip', 'update_time', 'create_time'
        ])->append(['dept_name', 'jobs_name','role_id', 'role_name'])->findOrEmpty($params['id'])->toArray();

        if ($action == 'detail') {
            return $admin;
        }

        $result['user'] = $admin;
        // 当前管理员角色拥有的菜单
        $result['menu'] = MenuService::getMenuByAdminId($params['id']);
        // 当前管理员角色拥有的按钮权限
        $result['permissions'] = AuthService::getBtnAuthByRoleId($admin);
        return $result;
    }

    /**
     * 新增角色
     * @param $adminId
     * @param $roleIds
     * @throws \Exception
     */
    public static function insertRole($adminId, $roleIds)
    {
        if (!empty($roleIds)) {
            // 角色
            $roleData = [];
            foreach ($roleIds as $roleId) {
                $roleData[] = [
                    'admin_id' => $adminId,
                    'role_id' => $roleId,
                ];
            }
            (new AdminRole())->saveAll($roleData);
        }
    }

    /**
     * 修改密码
     * @param $account
     * @param $password
     * @return bool
     */
    public static function changePassword($account, $password) {

        $admin = Admin::where(['account' => $account])->field('id,account,password')->findOrEmpty()->toArray();
        if (!$admin) return self::setError('抱歉,未找到该账号信息!');

        $passwordSalt = com_get_config('unique_identification', 'core');
        $newPassword = password_encrypt($password, $passwordSalt);

        return Admin::edit(['password' => $newPassword],$admin['id']);
    }

}